using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;

namespace NExt.Serialization.JsonNet.Conversion
{
    /// <summary>
    /// JsonNet works with utc time, we need to convert it to local time.
    /// </summary>
    public class DateTimeConvertor : JavaScriptDateTimeConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is DateTime)
            {
                DateTime dateTime = (DateTime)value;
                long ticksUtc = dateTime.ToUniversalTime().Ticks;
                DateTime dateTimeUtc = new DateTime(ticksUtc, DateTimeKind.Utc);
                base.WriteJson(writer, dateTimeUtc, serializer);
                return;
            }

            base.WriteJson(writer, value, serializer);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            object result = base.ReadJson(reader, objectType, existingValue, serializer);
            if (result != null)
            {
                DateTime dateTimeUtc = (DateTime)result;
                DateTime localTime = dateTimeUtc.ToLocalTime();
                return localTime;
            }

            return result;
        }
    }
}